package com.emapp.lccode.activity

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.widget.DatePicker
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItems
import com.emapp.lccode.R
import com.emapp.lccode.adapter.MyOrderKtAdapter
import com.emapp.lccode.adapter.ProjectDeviceAdapter
import com.emapp.lccode.adapter.XunjianAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.OrderKt
import com.emapp.lccode.bean.SelectType
import com.emapp.lccode.databinding.ActivityProjectDeviceListBinding
import com.emapp.lccode.databinding.ActivityXunjianListBinding
import com.emapp.lccode.mode.OrderKtViewModel
import com.emapp.lccode.mode.ProjectDeviceViewModel
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.statesListall
import com.emapp.lccode.utils.toJsonStr
import com.emapp.lccode.utils.vertical
import com.emapp.lccode.view.ProjectDeviceTypeDialog
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Calendar

/**首页-巡检记录
 */
class XunjianListActivity :
    BaseActivity1<OrderKtViewModel, ActivityXunjianListBinding>(),
    OnDateSetListener, ProjectDeviceTypeDialog.SelectTypeListener {
    private val projectAdapter: XunjianAdapter by lazy { XunjianAdapter() }
    var datas: ArrayList<OrderKt> = arrayListOf()
    var start_time = ""
    var end_time = ""
    var keywords = ""
    var status = ""
    var page = 1
    private var time_flag=1
    private lateinit var dialog: DatePickerDialog
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        initCalendar()
//        project_id = intent.getStringExtra("project_id").toString()
//        project_name = intent.getStringExtra("project_name").toString()
        mViewBind.lvTitle.tvTitle.text = "巡检日志"
        mViewBind.lvTitle.tvRight.text = ""
        EventBus.getDefault().register(this)
        mViewBind.rvList.run {
            vertical()
            adapter = projectAdapter
        }
        projectAdapter.run {
            setOnItemClickListener { adapter, _, position ->
                val item = adapter.items[position]
                val intent =
                    Intent(this@XunjianListActivity, XunjianInforKtActivity::class.java)
                intent.putExtra("id", item.id)
                //intent.putExtra("infor", item)
                //MmkvUtil.putString("infor",item.toJsonStr())
                startActivity(intent)
            }
            isEmptyViewEnable = true
            emptyView = layoutInflater.inflate(R.layout.listitem_empty, mViewBind.rvList, false)
        }
        mViewBind.refreshLayout.run {
            setRefreshHeader(ClassicsHeader(this@XunjianListActivity))
            setRefreshFooter(ClassicsFooter(this@XunjianListActivity))
            setOnRefreshListener {
                page = 1
                getList()
            }
            setOnLoadMoreListener {
                page++
                getList()
            }
        }
        showLoading()
        getList()
        mViewBind.tvSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keywords = v.text.toString().trim()
                showLoading()
                page = 1
                getList()
                true
            } else {
                false
            }
        }
    }
    private fun initCalendar() {
        val calendar = Calendar.getInstance()
        dialog = DatePickerDialog(
            this, this, calendar[Calendar.YEAR] //年份
            , calendar[Calendar.MONTH] //月份
            , calendar[Calendar.DAY_OF_MONTH]
        ) //日子
    }
    private fun getList() {
        mViewModel.getxunjianList(start_time, end_time, status, keywords, page)
    }

    override fun createObserver() {
        mViewModel.run {
            xunjians.observe(
                this@XunjianListActivity,
                Observer { resultState ->
                    parseState(resultState, {
                        if (page == 1) {
                            datas.clear()
                            if (it.data != null) {
                                datas.addAll(it.data)
                                if (it.data.size < BaseConfig.page_count) {
                                    mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                                } else {
                                    mViewBind.refreshLayout.finishRefresh()
                                }
                            } else {
                                mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                            }
                        } else {
                            if (it.data != null) {
                                datas.addAll(it.data)
                                if (it.data.size < BaseConfig.page_count) {
                                    mViewBind.refreshLayout.finishLoadMoreWithNoMoreData()
                                } else {
                                    mViewBind.refreshLayout.finishLoadMore()
                                }
                            } else {
                                mViewBind.refreshLayout.finishLoadMoreWithNoMoreData()
                            }
                        }
                        projectAdapter.submitList(datas)
                        projectAdapter.notifyDataSetChanged()
                    }, {
                        Toaster.show(it.errorMsg)
                        mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                    })
                })
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @SuppressLint("CheckResult")
    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.btSearch,
            mViewBind.tvStart,
            mViewBind.tvEnd,
            mViewBind.lvTitle.tvRight
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }

                R.id.tv_right -> {
                }

                R.id.tv_start -> {
                    time_flag = 1
                    dialog.show()
                }

                R.id.tv_end -> {
                    time_flag = 2
                    dialog.show()
                }

                R.id.bt_search -> {
                    keywords = mViewBind.tvSearch.text.toString().trim()
                    showLoading()
                    page = 1
                    getList()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.REFRESH_PROJECT_DEVICE -> {
                page = 1
                getList()
            }

            else -> {}
        }
    }


    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        //val desc = String.format("%s-%02d-%02d", year, month + 1, dayOfMonth)
        val desc = String.format("%s-%02d-%02d", year, month + 1, dayOfMonth)
        if (time_flag == 1) {
            mViewBind.tvStart.text=desc
            start_time=desc
            page=1
            getList()
        } else {
            mViewBind.tvEnd.text=desc
            end_time=desc
            page=1
            getList()
        }
    }

    override fun onSelectTypeComplete(type: SelectType) {
    }

}
